package day18;

import java.util.concurrent.atomic.AtomicInteger;

//模拟乐观锁 : 计数器
public class Demo6 {
    //是原子类：具有原子操作
    AtomicInteger count = new AtomicInteger(0);
    public void increment() {
        String name = Thread.currentThread().getName();
        int currentValue;//当前值
        int newValue;//最新的值
        while(true){
            currentValue = count.get();//获取当前值
            //如果可以修改  要把计数器的数据也修改
            newValue = currentValue + 1;
            //表示尝试修改：计算器的值 和 currentValue是一样的
            //说明没有被人改过  那么计数器就可以尝试更新成newValue
            //否则更新失败
            boolean b =  count.compareAndSet(currentValue, newValue);
            if(b)
//            {System.out.println(name + "尝试更新成功，当前值:"+currentValue+
//                    ",计数器:"+count.get());break;}
                break;
            else {System.out.println(name + "尝试更新失败，当前值:"+currentValue+
                    ",计数器:"+count.get()+",被其他线程修改了");}
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Demo6 demo6 = new Demo6();
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                demo6.increment();
            }
        },"A");
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                demo6.increment();
            }
        },"B");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("最终："+demo6.count.get());
    }
}
